package com.fjnldx.mes.service.scddglService;

import com.fjnldx.mes.domain.domainReq.*;
import com.fjnldx.mes.domain.domainRes.*;
import com.fjnldx.mes.domain.pojo.*;
import com.fjnldx.mes.mapper.scddglMapper.SecMapper;
import com.fjnldx.mes.utils.Common;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Service
@Transactional(rollbackFor = Exception.class)
public class SecService {
    @Resource
    SecMapper secMapper;
    @Resource
    Common common;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 订单查询
     */
    public Result queryOrder(Order data) throws Exception {
        try {
            List<Order> list = secMapper.queryOrder(data);
            for (Order order : list) {
                if ("true".equals(order.getMerge())) {  // 为合并订单
                    OrderSec query = new OrderSec();
                    query.setOriddbh(order.getDdbh());
                    query.setSize(-1);
                    List<OrderSec> orderSecs = secMapper.queryOrderSec(query); // 二级订单列表
                    // 总重
                    double zl_sum = orderSecs.stream().mapToDouble(OrderSec::getZl).sum();
                    BigDecimal bigDecimal = new BigDecimal(zl_sum);
                    double zl_sum_format = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                    order.setZl(zl_sum_format);
                    secMapper.updateOrder(order); // 更新
                }
            }
            list = secMapper.queryOrder(data); //重新查询
            int total = secMapper.queryTotalOrder(data);
            ResultObject<Order> res = new ResultObject<>();
            res.setDataList(list);
            res.setTotal(total);
            return Result.success(res);
        } catch (Exception e) {
            throw new Exception();
        }

    }

    /**
     * 删除订单
     */
    public Result deleteOrder(ArrayReq arrayReq) throws Exception {
        try {
            String[] ddbhs = arrayReq.getDdbhs();
            int i = secMapper.deleteOrder(ddbhs); // 删除一级订单
            secMapper.deleteOrderSecOri(ddbhs); // 删除二级订单
            return i > 0 ? Result.success("删除成功") : Result.error("无该订单编号");
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 更新订单
     */
    public Result updateOrder(Order data) throws Exception {
        try {
            data.setUpdate_time(LocalDateTime.now());
            int i = secMapper.updateOrder(data);
            return i > 0 ? Result.success("更新成功") : Result.error("无该订单id");
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 新增订单
     */
    public Result insertOrder(Order data) throws Exception {
        try {
            Order query = new Order();
            query.setDdbh(data.getDdbh());
            int i = secMapper.queryTotalOrder(query);
            if (i > 0) {
                return Result.error("订单编号重复");
            }
            data.setMerge("false");
            data.setStatus("待下达");
            data.setUpdate_time(LocalDateTime.now());
            secMapper.insertOrder(data);
            return Result.success("新增成功");
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 二级订单查询
     */
    public Result queryOrderSec(OrderSec data) throws Exception {
        try {
            if (data.getOriddbh() == null || "".equals(data.getOriddbh())) {
                return Result.error("查询二级订单列表时，原订单编号oriddbh不能为空");
            }
            List<OrderSec> list = secMapper.queryOrderSec(data);
            int total = secMapper.queryTotalOrderSec(data);
            ResultObject<OrderSec> res = new ResultObject<>();
            res.setDataList(list);
            res.setTotal(total);
            return Result.success(res);
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 新增二级订单
     */

    public Result insertOrderSec(ArrayReq arrayReq) throws Exception {
        try {
            String[] array = arrayReq.getDdbhs();
            String oriddbh = arrayReq.getOriddbh();
            OrderSec query_sec = new OrderSec();
            query_sec.setOriddbh(oriddbh);
            int total_sec = secMapper.queryTotalOrderSec(query_sec);
            if (total_sec == 0) {
                return Result.error("不存在该原订单编号");
            }
            for (String item : array) {
                Order query = new Order();
                query.setDdbh(item);
                query.setSize(-1);
                List<Order> list = secMapper.queryOrder(query);
                if (list.size() == 0) {
                    return Result.error("不存在该订单编号");
                }
                Order order = list.get(0);
                OrderSec orderSec = new OrderSec();
                BeanUtils.copyProperties(order, orderSec);
                orderSec.setOriddbh(oriddbh);
                secMapper.insertOrderSec(orderSec);
            }
            secMapper.deleteOrder(array);
            Order q_params = new Order();
            q_params.setDdbh(oriddbh);
            q_params.setSize(-1);
            Order u_order = secMapper.queryOrder(q_params).get(0);
            u_order.setUpdate_time(LocalDateTime.now());
            secMapper.updateOrder(u_order); // 更新操作时间
            return Result.success("新增成功");
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 更新二级订单
     */
    public Result updateOrderSec(OrderSec data) throws Exception {
        try {
            secMapper.updateOrderSec(data);
            secMapper.updateOrderUpdateTime(data.getOriddbh());  // 更新一级操作时间
            secMapper.updateOrderUpdateTimeSec(data.getOriddbh(), data.getDdbh()); // 更新二级操作时间
            return Result.success("更新成功");
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 删除二级订单
     */
    public Result deleteOrderSec(ArrayReq arrayReq) throws Exception {
        try {
            String[] ddbhs = arrayReq.getDdbhs();
            String oriddbh = arrayReq.getOriddbh();
            secMapper.deleteOrderSec(ddbhs, oriddbh); // 删除二级订单
            DeleteStatus status = new DeleteStatus();
            status.setEmpty(false);
            OrderSec query = new OrderSec();
            query.setOriddbh(oriddbh);
            int total = secMapper.queryTotalOrderSec(query);
            if (total == 0) {
                String[] array = new String[1];
                array[0] = oriddbh;
                secMapper.deleteOrder(array);
                status.setEmpty(true);
            }
            secMapper.updateOrderUpdateTime(oriddbh);  // 更新一级操作时间
            status.setMessage("删除成功");
            return Result.success(status);
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 合并订单
     */
    public Result mergeOrder(DdbhArray array) throws Exception {
        try {
            // 生成新订单编号
            String newDdbh = "H" + (int) ((Math.random() * 9 + 1) * 100000);
            ArrayList<OrderSec> saveList = new ArrayList<>(); // 二级订单存放List
            for (String ddbh : array.getDdbhs()) { // 遍历订单编号
                Order query = new Order();
                query.setDdbh(ddbh);
                query.setSize(-1);
                List<Order> list = secMapper.queryOrder(query);// 查一级订单详情
                if (list.size() == 0) {
                    return Result.error("不存在改订单编号");
                }
                Order order = list.get(0); // 获取该一级订单
                if ("true".equals(order.getMerge())) {
                    return Result.error("存在已合并的订单");
                }
                if ("已下达".equals(order.getStatus())) {
                    return Result.error("已下达的订单不能合并");
                }
                OrderSec orderSec = new OrderSec();
                orderSec.setOriddbh(newDdbh);
                BeanUtils.copyProperties(order, orderSec);
                saveList.add(orderSec);   // 符合条件，保存
            }

            // 合并前检验
            for (int i = 0; i < saveList.size() - 1; i++) {
                if (!Objects.equals(saveList.get(i).getOrg(), saveList.get(i + 1).getOrg())) {
                    return Result.error("组织不一致");
                }
                if (!Objects.equals(saveList.get(i).getPz(), saveList.get(i + 1).getPz())) {
                    return Result.error("品种名称不一致");
                }
                if (!Objects.equals(saveList.get(i).getZb(), saveList.get(i + 1).getZb())) {
                    return Result.error("支别不一致");
                }
                if (!Objects.equals(saveList.get(i).getStatus(), "待下达")) {
                    return Result.error("需为待下达订单");
                }
            }
            for (OrderSec orderSec : saveList) {
                secMapper.insertOrderSec(orderSec); // 插入二级
                secMapper.deleteOrder(array.getDdbhs()); // 删除一级
            }
            // 总重
            double zl_sum = saveList.stream().mapToDouble(OrderSec::getZl).sum();
            BigDecimal bigDecimal = new BigDecimal(zl_sum);
            double zl_sum_format = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            // 拷贝
            OrderSec t_orderSec = saveList.get(0);
            Order i_order = new Order();
            BeanUtils.copyProperties(t_orderSec, i_order);
            i_order.setDdbh(newDdbh);
            i_order.setZl(zl_sum_format);
            i_order.setMerge("true");
            i_order.setUpdate_time(LocalDateTime.now()); // 更新一级操作时间
            secMapper.insertOrder(i_order); // 插入一级
            return Result.success("合并订单成功");
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 获取当前空闲机台
     */
    public Result getFreeDev() throws Exception {
        try {
            ArrayList<DevDictionary> freeDev = new ArrayList<>();
            List<DevDictionary> devList = secMapper.queryDevDictionary();
            for (DevDictionary dev : devList) {
                String key = dev.getGongxu() + dev.getDevSn();
                if (!common.isExistKey(key)) {
                    freeDev.add(dev);
                }
            }
            return Result.success(freeDev);
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 下达预排计划
     */
    public Result releasePrePlan(PrePlan data) throws Exception {
        try {
            // 生成预排计划编号
            String newPreBh = "PRE" + (int) ((Math.random() * 9 + 1) * 100000);
            LocalDate dBegin = data.getStart_time();
            LocalDate dEnd = data.getEnd_time();
            List<LocalDate> lDate = common.getBetweenDate(dBegin, dEnd);
            for (LocalDate date : lDate) {
                PrePlan i_params = new PrePlan();
                BeanUtils.copyProperties(data, i_params);
                i_params.setTime(date);
                i_params.setPre_bh(newPreBh);
                i_params.setUpdate_time(LocalDateTime.now());
                i_params.setStatus("待下达");
                i_params.setStart_time(dBegin);
                i_params.setEnd_time(dEnd);
                // 新增预排计划
                secMapper.insertPrePlan(i_params);
            }
            return Result.success("下达至预排计划成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 预排计划查询
     */
    public Result queryPrePlan(PrePlanQuery data) throws Exception {
        try {
            List<PrePlanRes> list = secMapper.queryPrePlan(data);
            int total = secMapper.queryPrePlanTotal(data);
            ResultObject<PrePlanRes> res = new ResultObject<>();
            res.setDataList(list);
            res.setTotal(total);
            return Result.success(res);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 删除预排计划记录
     */
    public Result deletePrePlan(String[] array) throws Exception {
        try {
            secMapper.deletePrePlan(array);
            return Result.success("删除成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 修改预排计划
     */
    public Result modifyPrePlan(ModifyPrePlanReq data) throws Exception {
        try {
            secMapper.modifyPrePlan(data);
            return Result.success("更新成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 新增预排计划-根据订单编号查询订单信息
     */
    public Result queryOrderInfoByOrderNumber(String ddbh) throws Exception {
        try {
            List<OrderInfo> list = secMapper.queryOrderInfoByOrderNumber(ddbh);
            if (list.size() == 0) {
                return Result.error("不存在改订单");
            }
            return Result.success(list);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 根据订单编号取消预排计划
     *
     * @param data 订单编号
     * @return
     * @throws Exception
     */
    public Result deletePrePlanByOrder(String data) throws Exception {
        try {
            Order order = new Order();
            order.setDdbh(data);
            order.setSize(-1);
            List<Order> list = secMapper.queryOrder(order);
            for (Order item : list) {
                updateOrderStatus(item.getId(), "已取消");
            }
            secMapper.deletePrePlanByOrder(data);
            return Result.success("删除成功");
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 更新订单状态
     */
    public void updateOrderStatus(Integer id, String status) throws Exception {
        try {
            Order order = new Order();
            order.setId(id);
            order.setSize(-1);
            List<Order> q_list = secMapper.queryOrder(order);
            OrderSec orderSec = new OrderSec();
            orderSec.setOriddbh(q_list.get(0).getDdbh());
            // 更新二级订单状态
            List<OrderSec> q_orderSecs = secMapper.queryOrderSec(orderSec);
            for (OrderSec item : q_orderSecs) {
                item.setStatus(status);
                secMapper.updateOrderSec(item);
            }
            // 更新一级订单状态
            order.setStatus(status);
            secMapper.updateOrder(order);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new Exception();
        }
    }

    /**
     * 设置机台工作时间
     */
    //public Result setDevWorkTime(List<DevWork> devWorkList) throws Exception {
    //    try {
    //        for (DevWork devWork : devWorkList) {
    //            Date date = new Date();
    //            if (devWork.getTime().compareTo(date) >= 0) {
    //                String key = devWork.getGongxu() + devWork.getDevSn();
    //                int seconds = common.getSeconds(devWork.getTime());
    //                System.out.println(seconds);
    //                common.setKeyLifeTime(key, "正在工作中", seconds); // 设置设备状态
    //                secMapper.insertScjh(devWork); // 插入生产计划
    //                //secMapper.insertScjhRenyuan(devWork); // 维护人员
    //            } else {
    //                throw new ProcessException("计划时间小于当前时间");
    //            }
    //
    //        }
    //        return Result.success(devWorkList.size() + "设置成功");
    //    } catch (Exception e) {
    //        throw new Exception();
    //    }
    //}

    /**
     * 根据细纱品种和重量获取其他工序品种重量
     *
     * @return Result
     */
    //public List<WeightResult> getWeightByPz(String pz, String weight, Date ddjq) {
    //    Date now = new Date();
    //    // 剩余天数
    //    BigDecimal reDays = new BigDecimal(ddjq.getDate() - now.getDate());
    //    BigDecimal bWeight = new BigDecimal(weight);
    //    ArrayList<WeightResult> resultList = new ArrayList<>();
    //    // 细纱
    //    WeightResult xiSha = new WeightResult();
    //    BigDecimal xiShaAvg = bWeight.divide(reDays, 2, BigDecimal.ROUND_HALF_UP);
    //    xiSha.setGongxu("细纱");
    //    // 总重量
    //    xiSha.setWeight(weight);
    //    // 平均每天产量
    //    xiSha.setAvgOutPut(xiShaAvg.toString());
    //    resultList.add(xiSha);
    //    // 粗纱-weight/xiaolv
    //    WeightResult cuSha = new WeightResult();
    //    BigDecimal cuShaEff = new BigDecimal("1.02");// 从定额表中获取
    //    BigDecimal cuShaWeight = bWeight.divide(cuShaEff, 2, BigDecimal.ROUND_HALF_UP);
    //    BigDecimal cuShaAvg = cuShaWeight.divide(reDays, 2, BigDecimal.ROUND_HALF_UP);
    //    cuSha.setGongxu("粗纱");
    //    cuSha.setWeight(cuShaWeight.toString());
    //    cuSha.setAvgOutPut(cuShaAvg.toString());
    //    resultList.add(cuSha);
    //    // 并条
    //    WeightResult bT = new WeightResult();
    //    bT.setGongxu("并条");
    //    bT.setWeight(weight);
    //    resultList.add(bT);
    //    // 梳棉
    //    WeightResult sM = new WeightResult();
    //    sM.setGongxu("梳棉");
    //    sM.setWeight(weight);
    //    resultList.add(sM);
    //    // 清联
    //    WeightResult qL = new WeightResult();
    //    qL.setGongxu("清联");
    //    qL.setWeight(weight);
    //    resultList.add(qL);
    //    // 络筒
    //    WeightResult Lt = new WeightResult();
    //    Lt.setGongxu("络筒");
    //    Lt.setWeight(weight);
    //    resultList.add(Lt);
    //    return resultList;
    //}


    ///**
    // * 二级预排计划删除
    // */
    //public Result deleteYpjhSec(ArrayReq arrayReq) {
    //    Result result = new Result();
    //    try {
    //        String[] ddbhs = arrayReq.getDdbhs();
    //        int i = secMapper.deleteYpjhSec(ddbhs);// 删除二级预排计划
    //        for (String ddbh : ddbhs) {
    //            DdglSecReq ddglSecReq = new DdglSecReq();
    //            ddglSecReq.setDdbh(ddbh);
    //            List<FzyDdglSec> fzyDdglSecs = secMapper.queryDdglSec(ddglSecReq);
    //            FzyDdglSec fzyDdglSec = new FzyDdglSec();
    //            fzyDdglSec.setId(fzyDdglSecs.get(0).getId());
    //            System.out.println(fzyDdglSecs.get(0).getId());
    //            fzyDdglSec.setStatus("已取消");
    //            secMapper.updateDdSec(fzyDdglSec); // 更新订单管理二级订单状态
    //        }
    //        if (i > 0) {
    //            result.setCode(1);
    //            result.setStatus("success");
    //            result.setData(i);
    //            result.setMsg("删除成功");
    //        } else {
    //            throw new ProcessException("无该订单编号");
    //        }
    //    } catch (Exception e) {
    //        result.setCode(-1);
    //        result.setStatus("error");
    //        result.setMsg(e.getMessage());
    //    }
    //    return result;
    //}

    /**
     * 生产计划查询
     */
    public Result queryScjh(MesNewscjhInfo data) throws Exception {
        try {
            List<MesNewscjhInfo> list = secMapper.queryScjh(data);
            int total = secMapper.queryTotalScjh(data);
            if (total > 0) {
                ResultObject<MesNewscjhInfo> res = new ResultObject<>();
                res.setDataList(list);
                res.setTotal(total);
                return Result.success(res);
            } else {
                return Result.success(null);
            }
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 根据品种进行定额查询
     */
    public Result queryDingErByPzAndGongxu(DingerReq data) throws Exception {
        try {
            List<MesDinger> list = secMapper.queryDingErByPzAndGongxu(data);
            if (list.size() > 0) {
                return Result.success(list);
            } else {
                return Result.success(null);
            }
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 删除生产计划 id
     */
    public Result deleteScjh(String[] array) throws Exception {
        try {
            int i = secMapper.deleteScjh(array);
            if (i > 0) {
                return Result.success("删除成功");
            } else {
                return Result.error("无该id");
            }
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 新增生产计划
     */
    public Result insertScjh(MesNewscjhInfo data) throws Exception {
        try {
            // 生成生产计划编号
            String bh = "SC" + (int) ((Math.random() * 9 + 1) * 100000);
            Gson gson = new Gson();
            MesNewscjhInfo info = gson.fromJson(gson.toJson(data), MesNewscjhInfo.class);
            info.setDevSn(Arrays.toString(data.getDevSnAreaArray()));
            info.setScjhbh(bh);
            secMapper.insertScjh2(info);  // 插入生产计划一级
            String[] array = data.getDevSnAreaArray();
            for (String devSn : array) {
                MesNewscjhInfo info2 = gson.fromJson(gson.toJson(data), MesNewscjhInfo.class);
                info2.setDevSn(devSn);
                info2.setScjhbh(bh);
                System.out.println(info2.toString());
                secMapper.insertScjhSec(info2);  // 插入生产计划二级
            }
            return Result.success("新增成功");
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 更新生产计划
     */
    public Result upDateScjh(MesNewscjhInfo data) throws Exception {
        try {
            data.setDevSn(Arrays.toString(data.getDevSnAreaArray()));
            int i = secMapper.updateScjh(data);
            if (i > 0) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            throw new Exception();
        }
    }

    /**
     * 生产计划查询-二级
     */
    public Result queryScjhSec(MesNewscjhInfo data) throws Exception {
        try {
            List<MesNewscjh> list = secMapper.queryScjhSec(data);
            int total = secMapper.queryTotalScjhSec(data);
            if (total > 0) {
                ResultObject<MesNewscjh> res = new ResultObject<>();
                res.setDataList(list);
                res.setTotal(total);
                return Result.success(res);
            } else {
                return Result.success(null);
            }
        } catch (Exception e) {
            throw new Exception();
        }
    }
}
